var TranslationEdit = new (function() {
	
	var ID = {
		TONES: '.tone',
		AC_KANA: '#ac_kana',
		
		TONE: '#term_tone',
		TD_TONE: '#td_tone',
		PRONUNCIATION: '#term_pronunciation_romaji'
	};
	
	var acKana;
	
	this.init = function() {
		$(ID.TONES).click(onToneClick);
		acKana = AutocompleteInput.get(ID.AC_KANA);

		acKana.setOptions({
			select: onKanaSelect
		});
		
		acKana.getInputText().keyup(onChangeKana);
		$(ID.TD_TONE).mousedown(function(e) { e.preventDefault(); });
	}
	$(document).ready(this.init);
	
	function onKanaSelect(item) {
		var term = item.term;
		$(ID.TD_TONE).html(term.tone_html);
		$(ID.TONE).val(term.tone);
		$(ID.PRONUNCIATION).val(term.pronunciation_romaji);
		
		item.value = term.kana;
		
		$(ID.TONES).click(onToneClick);
		// return false;
	}
	
	function onToneClick() {
		var t = $(this);
		if (t.hasClass("up")) {
			t.removeClass("up");
		}
		else if (t.hasClass("down")) {
			t.removeClass("down");
			t.addClass("up");
		}
		else {
			t.addClass("down");
		}
		
		saveTone();
		
		return false;
	}
	
	function saveTone() {
		var tones = $(ID.TONES);
		var notempty = false;
		var valtone = "";
		for (var i = 0; i < tones.length; i++) {
			var tone = $(tones[i]);
			if (tone.hasClass("up")) {
				notempty = true;
				valtone += "u";
			} else if (tone.hasClass("down")) {
				notempty = true;
				valtone += "d";
			} else {
				valtone += " ";
			}
		}

		$(ID.TONE).val(valtone);
	}
	
	function createToneFromKana(kana) {
		var html = "";
		for (var i = 0; i < kana.length; i++) {
			html += '<span class="tone">'+kana[i]+'</span>';
		}
		$(ID.TD_TONE).html(html);
		$(ID.TONES).click(onToneClick);
	}
	
	function onChangeKana() {
		var input = $(this);
		createToneFromKana(input.val());
	}
	
	
});